package com.xxrl.shop.config.handler;

import com.alibaba.fastjson.JSON;
import com.xxrl.shop.common.entity.JsonResult;
import com.xxrl.shop.common.utils.ResultTool;
import com.xxrl.shop.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author mis
 */
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final UserService userService;

    public CustomizeAuthenticationSuccessHandler(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {

        String username = ((User) authentication.getPrincipal()).getUsername();
        com.xxrl.shop.domain.User user = userService.getUserByName(username);
        JsonResult<String> result = ResultTool.success();
        result.setData(user.getRole());
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}
